<template>
  <div class="user-center-container">
    <h2>用户中心</h2>
    <div v-if="!user" class="user-card">
      未登录，请先登录
      <br>
      <button class="login-btn" @click="router.push('/login')">登录</button>
      </br>
    </div>
    <div v-else class="user-card">
      <div class="avatar-upload">
        <img :src="user.avatar || '/src/assets/vue.svg'" alt="用户头像" class="user-avatar" />
        <input type="file" accept="image/*" @change="onAvatarChange" />
      </div>
      <div class="user-info">
        <div class="user-name">用户名：{{ user.username }}</div>
        <div class="user-email">邮箱：{{ user.email }}</div>
        <div class="user-phone">手机号：{{ user.phone }}</div>
        <button @click="showEdit = true">修改信息</button>
        <button @click="showPwd = true">重置密码</button>
        <button @click="logout">退出登录</button>
      </div>
    </div>

    <!-- 修改信息弹窗 -->
    <div v-if="showEdit" class="modal">
      <div class="modal-content">
        <h3>修改信息</h3>
        <form @submit.prevent="handleUpdate">
          <label>邮箱：</label>
          <input v-model="editEmail" type="email" required />
          <label>手机号：</label>
          <input v-model="editPhone" type="tel" />
          <button type="submit">保存</button>
          <button type="button" @click="showEdit = false">取消</button>
        </form>
        <div v-if="editMsg" class="msg">{{ editMsg }}</div>
      </div>
    </div>

    <!-- 重置密码弹窗 -->
    <div v-if="showPwd" class="modal">
      <div class="modal-content">
        <h3>重置密码</h3>
        <form @submit.prevent="handleResetPwd">
          <label>新密码：</label>
          <input v-model="newPwd" type="password" required minlength="6" />
          <button type="submit">确定</button>
          <button type="button" @click="showPwd = false">取消</button>
        </form>
        <div v-if="pwdMsg" class="msg">{{ pwdMsg }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
const avatarFile = ref<File|null>(null);
const avatarMsg = ref('');

const onAvatarChange = async (e: Event) => {
  const files = (e.target as HTMLInputElement).files;
  if (!files || files.length === 0) return;
  avatarFile.value = files[0];
  const formData = new FormData();
  formData.append('avatar', avatarFile.value);
  try {
    const res = await axios.post('/api/user/upload-avatar', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    user.value.avatar = res.data.url;
    avatarMsg.value = '头像上传成功';
    setTimeout(() => avatarMsg.value = '', 1200);
  } catch (e: any) {
    avatarMsg.value = e.response?.data?.message || '上传失败';
  }
};
import { ref, onMounted } from 'vue';
import axios from '../api/axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const user = ref<any>(null);
const showEdit = ref(false);
const showPwd = ref(false);
const editEmail = ref('');
const editPhone = ref('');
const editMsg = ref('');
const newPwd = ref('');
const pwdMsg = ref('');

function userId() {
  return user.value?.id || '';
}

const getUserId = () => {
  // 优先从 localStorage 获取 userId
  return localStorage.getItem('userId') || user.value?.id || '';
};

const fetchUser = async () => {
  try {
    const token = localStorage.getItem('token');
    const id = getUserId();
    if (!token || !id) {
      user.value = null;
      router.push('/login');
      return;
    }
    const res = await axios.get(`/api/user/${id}`);
    user.value = res.data;
    // 若本地没有 userId，则补充存储
    if (!localStorage.getItem('userId') && user.value?.id) {
      localStorage.setItem('userId', user.value.id);
    }
  } catch {
    user.value = null;
    router.push('/login');
  }
};

const handleUpdate = async () => {
  editMsg.value = '';
  try {
    await axios.put('/api/user/update', {
      id: user.value.id,
      username: user.value.username,
      email: editEmail.value,
      phone: editPhone.value,
    });
    user.value.email = editEmail.value;
    user.value.phone = editPhone.value;
    editMsg.value = '修改成功';
    setTimeout(() => { showEdit.value = false; editMsg.value = ''; }, 1200);
  } catch (e: any) {
    editMsg.value = e.response?.data?.message || '修改失败';
  }
};

const handleResetPwd = async () => {
  pwdMsg.value = '';
  try {
    const res = await axios.post('/api/user/reset-password', {
      userId: user.value.id,
      newPassword: newPwd.value,
    });
    pwdMsg.value = '密码重置成功';
    setTimeout(() => { showPwd.value = false; pwdMsg.value = ''; newPwd.value = ''; }, 1200);
  } catch (e: any) {
    pwdMsg.value = e.response?.data?.message || '重置失败';
  }
};

const logout = () => {
  localStorage.removeItem('token');
  user.value = null;
  router.push('/login');
};

onMounted(() => {
  fetchUser();
  editEmail.value = user.value?.email || '';
  editPhone.value = user.value?.phone || '';
});
</script>

<style scoped>
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0,0,0,0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}
.modal-content {
  background: #fffbe6;
  padding: 32px 24px;
  border-radius: 16px;
  box-shadow: 0 4px 24px #ffe7ba;
  min-width: 320px;
}
.msg {
  color: #faad14;
  margin-top: 12px;
}
.user-center-container {
  max-width: 1200px;
  margin: 40px auto;
  padding: 32px;
  border-radius: 16px;
  box-shadow: 0 4px 24px #ffe7ba;
  background: #fffbe6;
  min-height: 480px;
}
.user-card {
  display: flex;
  align-items: center;
  gap: 32px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #ffd591;
  padding: 24px;
}
.user-avatar {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 50%;
  box-shadow: 0 2px 8px #ffd591;
}
.user-info {
  flex: 1;
}
.user-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
.user-email {
  font-size: 16px;
  margin-bottom: 16px;
}
.user-card button {
  background: #ff6600;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 10px 24px;
  font-size: 16px;
  cursor: pointer;
}
.login-btn {
  margin-top: 18px;
  background: #ff6600;
  color: #fff;
  border: none;
  border-radius: 10px;
  padding: 10px 32px;
  font-size: 1.1rem;
  font-weight: bold;
  box-shadow: 0 2px 8px #ffd591;
  cursor: pointer;
  transition: background 0.2s;
}
.login-btn:hover {
  background: #ff8500;
}
</style>
